package io.renren.service.impl;

import com.alibaba.fastjson.JSON;
import io.renren.entity.SysConfigEntity;
import io.renren.repository.SysConfigRepository;
import io.renren.service.SysConfigService;
import io.renren.utils.RRException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("sysConfigService")
public class SysConfigServiceImpl extends BaseServiceImpl<SysConfigEntity> implements SysConfigService {
    @Autowired
	private SysConfigRepository sysConfigRepository;

    @Override
    public void updateValueByKey(String key, String value) {
		sysConfigRepository.updateValueByKey(key, value);
    }


    @Override
    public String getValue(String key, String defaultValue) {
        String value = sysConfigRepository.queryByKey(key);
		if (StringUtils.isBlank(value)) {
            return defaultValue;
        }
        return value;
    }

    @Override
    public <T> T getConfigObject(String key, Class<T> clazz) {
        String value = getValue(key, null);
        if (StringUtils.isNotBlank(value)) {
            return JSON.parseObject(value, clazz);
        }

        try {
            return clazz.newInstance();
        } catch (Exception e) {
            throw new RRException("获取参数失败");
        }
    }
}
